package boot

import (
	"fmt"
	appConfig "yunj/app/queue/config"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/model"
	yunjAppConfig "yunj/pkg/yunj/app/queue/config"
	"yunj/pkg/yunj/core/log"
	"yunj/pkg/yunj/core/queue"
)

// 初始化队列任务
func InitQueue() {
	queues := append(yunjAppConfig.Queues, appConfig.Queues...)
	// 获取数据库状态值
	var items []*model.Queue
	err := global.MySQL.Find(&items).Error
	if err != nil {
		panic(fmt.Sprintf("获取队列任务失败: %v", err))
	}
	itemsMap := make(map[string]*model.Queue)
	for _, item := range items {
		itemsMap[item.Name] = item
	}
	for _, q := range queues {
		if item, exists := itemsMap[q.Name()]; exists {
			err = q.SetHandleStatus(item.Status)
		} else {
			err = q.SetHandleStatus(q.DefaultHandleStatus())
		}
		if err != nil {
			panic(fmt.Sprintf("%s状态设置异常: %v", q.LogPrefix(), err))
		}
	}
	err = queue.JobScheduler.Start(queues)
	if err != nil {
		panic(fmt.Sprintf("队列任务执行失败: %v", err))
	}
	log.Info("队列任务执行开始...")
}
